<template>
  <div class="dashboard-container">
    <h2>{{ type === "add" ? "新增问卷" : "修改问卷" }}</h2>
    <div class="dashboard-text">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入标题"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述：" prop="introduce">
          <el-input
            v-model="ruleForm.introduce"
            placeholder="请输入描述"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="总分：" prop="score">
          <el-input
            v-model="ruleForm.score"
            :disabled="isDisabled"
            placeholder="请输入总分"
            type="number"
          />
        </el-form-item>

        <el-form-item label="状态：" prop="title">
          <el-switch
            v-model="ruleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item label="评级范围：" prop="scope">
          <div class="scope-box">
            <el-card
              v-for="(item, index) in ruleForm.scope"
              :key="index"
              class="scope-item"
            >
              <div slot="header" class="header">
                <el-form-item
                  label-width="80px"
                  label="标题"
                  :rules="[
                    {
                      required: true,
                      message: '请输入标题',
                      trigger: 'blur',
                    },
                  ]"
                  :prop="'scope.' + index + '.title'"
                >
                  <el-input
                    v-model="ruleForm.scope[index].title"
                    placeholder="请输入选择标题"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
                <el-button
                  v-if="ruleForm.list.length !== 1"
                  style="margin-left: 10px"
                  type="text"
                  @click="delScope(item)"
                >删除</el-button>
              </div>
              <el-form-item
                label-width="100px"
                label="最小范围"
                :rules="[
                  {
                    required: true,
                    message: '最小范围',
                    trigger: 'blur',
                  },
                ]"
                :prop="'scope.' + index + '.min'"
              >
                <el-input
                  v-model="ruleForm.scope[index].min"
                  :disabled="isDisabled"
                  placeholder="请输入最小范围"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item
                label-width="100px"
                label="最大范围"
                :rules="[
                  {
                    required: true,
                    message: '最大范围',
                    trigger: 'blur',
                  },
                ]"
                :prop="'scope.' + index + '.max'"
              >
                <el-input
                  v-model="ruleForm.scope[index].max"
                  :disabled="isDisabled"
                  placeholder="请输入最大范围"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-card>
          </div>

          <el-button
            :disabled="isDisabled"
            type="text"
            @click="handleAddScope"
          >新增评级范围</el-button>
        </el-form-item>

        <el-form-item label="内容：" prop="list">
          <div class="box">
            <el-card
              v-for="(item, index) in ruleForm.list"
              :key="index"
              class="box-card"
            >
              <div slot="header" class="header">
                <div style="flex: 1">
                  <el-form-item
                    label-width="80px"
                    label="标题"
                    :rules="[
                      {
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur',
                      },
                    ]"
                    :prop="'list.' + index + '.title'"
                  >
                    <el-input
                      v-model="ruleForm.list[index].title"
                      placeholder="请输入选择标题"
                      maxlength="20"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item
                    label-width="80px"
                    label="分数"
                    :rules="[
                      {
                        required: true,
                        message: '请输入选择分数',
                        trigger: 'blur',
                      },
                    ]"
                    :prop="'list.' + index + '.score'"
                  >
                    <el-input
                      v-model="ruleForm.list[index].score"
                      :disabled="isDisabled"
                      style="margin-top: 10px"
                      placeholder="请输入选择分数"
                      type="number"
                    >
                      <template slot="append">分</template>
                    </el-input>
                  </el-form-item>
                </div>
                <el-button
                  v-if="ruleForm.list.length !== 1"
                  style="margin-left: 10px"
                  type="text"
                  @click="handleDelete(item)"
                >删除</el-button>
              </div>
              <el-radio-group v-model="ruleForm.list[index].result">
                <el-radio
                  v-for="o in item.options"
                  :key="o.id"
                  style="margin-top: 10px"
                  :label="o.id"
                >
                  <el-input
                    v-model="o.title"
                    :disabled="isDisabled"
                    placeholder="请输入选择标题"
                    maxlength="20"
                    show-word-limit
                  />

                  <el-button
                    v-if="item.options.length !== 1"
                    :disabled="isDisabled"
                    style="margin-left: 10px"
                    type="text"
                    @click="handleDeleteOption(item, o.id)"
                  >删除</el-button>
                </el-radio>
              </el-radio-group>

              <div>
                <el-button
                  v-if="item.options.length !== 0"
                  :disabled="isDisabled"
                  style="margin-left: 10px"
                  type="text"
                  @click="handleAddOption(item)"
                >添加选择</el-button>
              </div>
            </el-card>
          </div>
          <el-button
            type="text"
            :disabled="isDisabled"
            @click="handleAdd"
          >新增问卷内容</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveContent">保存</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="type !== 'add'" class="disabled-table">
      <h2>查看记录</h2>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f5f5' }"
      >
        <el-table-column label="评级范围" prop="result" />
        <el-table-column label="答案记录" prop="record" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="创建时间" prop="create_time" />
        <el-table-column label="更新时间" prop="update_time" />
        <el-table-column label="操作" prop="op">
          <template slot-scope="scope">
            <el-button
              type="danger"
              @click="handleToUserDetail(scope.row)"
            >查看</el-button>
            <el-button
              type="danger"
              @click="handleDel(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        :page-sizes="paginationConfig.pageSizes"
        :layout="paginationConfig.layout"
        :total="paginationConfig.total"
        :page="paginationConfig.page"
        :limit="paginationConfig.pageSize"
        @pagination="handleChangePage"
      />
    </div>
  </div>
</template>

<script>
import {
  addQuestionnaireDetail,
  delQuestionnaireRecord,
  getQuestionnaireDetail,
  getQuestionnaireRecordList,
  updateQuestionnaireDetail
} from '@/api/questionnaire'
export default {
  name: 'Dashboard',
  components: {},
  data() {
    return {
      ruleForm: {
        introduce: '',
        title: '',
        score: 100,
        state: 1,
        scope: [
          {
            min: 0,
            max: 20,
            title: '低级'
          }
        ], // 评级范围
        list: [
          {
            title: '默认标题一',
            score: 100,
            id: 1,
            result: 1,
            options: [
              {
                title: '默认选项一',
                id: 1
              },
              {
                title: '默认选项二',
                id: 2
              },
              {
                title: '默认选项三',
                id: 3
              },
              {
                title: '默认选项四',
                id: 4
              }
            ]
          }
        ]
      },
      contentId: null,
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        score: [{ required: true, message: '请输入总分', trigger: 'blur' }],
        scope: [
          {
            validator: (rule, value, callback) => {
              const hasOverlappingRanges = (rangeList) => {
                for (let i = 0; i < rangeList.length - 1; i++) {
                  for (let j = i + 1; j < rangeList.length; j++) {
                    const range1 = rangeList[i]
                    const range2 = rangeList[j]
                    // 检查两个范围是否有重叠
                    if (
                      !(
                        Number(range1.max) < Number(range2.min) ||
                        Number(range2.max) < Number(range1.min)
                      )
                    ) {
                      return true
                    }
                  }
                }

                return false
              }

              if (value.length === 0) {
                callback(new Error('请添加评级范围'))
              } else if (hasOverlappingRanges(value)) {
                callback(new Error('评级范围不能重叠'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        list: [
          {
            validator: (rule, value, callback) => {
              const { score } = this.ruleForm
              const curScore = value.reduce((pre, cur) => {
                return pre + Number(cur.score)
              }, 0)
              if (value.length === 0) {
                callback(new Error('请添加问卷内容'))
              } else if (Number(curScore) !== Number(score)) {
                callback(new Error('所有选项加起来的总分要等于总分'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      tableData: [],
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      }
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    isDisabled() {
      return this.type === 'edit'
    }
  },
  created() {
    this.handleGetUserDetail()
    this.handleGetRecordsList()
  },
  methods: {
    async handleGetUserDetail() {
      if (!this.$route.query.id) return
      const res = await getQuestionnaireDetail({
        id: this.$route.query.id
      })
      if (res.code === 200) {
        this.ruleForm = Object.assign({}, res.data)
      }
    },
    async handleGetRecordsList() {
      if (!this.$route.query.id) return
      const { page, pageSize } = this.paginationConfig
      const res = await getQuestionnaireRecordList({
        questionnaireId: this.$route.query.id,
        page,
        pageSize
      })
      if (res.code === 200) {
        console.log('========', res.data.list)
        res.data.list.map(v => {
          console.log()
          const arr = []
          v.record_options.map(v => {
            arr.push(`${v.title}：${v.value}`)
          })
          v.record = arr.join('；')
        })
        this.tableData = res.data.list
        this.total = res.data.total
      }
    },
    handleChangePage({ page, pageSize }) {
      this.paginationConfig.page = page
      this.paginationConfig.pageSize = pageSize
      this.handleGetRecordsList()
    },
    handleSaveContent() {
      this.$refs.ruleForm.validate(async(valid) => {
        console.log(valid)
        if (valid) {
          if (this.type === 'add') {
            const res = await addQuestionnaireDetail(this.ruleForm)
            if (res.code === 200) {
              this.$message.success(res.data)
              this.$router.back()
            }
          } else {
            const res = await updateQuestionnaireDetail(this.ruleForm)
            if (res.code === 200) {
              this.$message.success(res.data)
              this.$router.back()
            }
          }
        }
      })
    },
    async handleDel(e) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delQuestionnaireRecord({
          id: e.id
        })
        if (res.code === 200) {
          this.$message.success(res.data)
          this.handleGetRecordsList()
        }
      })
    },
    handleAdd() {
      this.ruleForm.list.push({
        title: '默认标题',
        score: 100,
        id: Date.now(),
        result: 1,
        options: [
          {
            title: '默认选项一',
            id: 1
          },
          {
            title: '默认选项二',
            id: 2
          },
          {
            title: '默认选项三',
            id: 3
          },
          {
            title: '默认选项四',
            id: 4
          }
        ]
      })
    },
    handleDelete(e) {
      this.ruleForm.list = this.ruleForm.list.filter(
        (item) => item.id !== e.id
      )
    },
    handleAddOption(e) {
      e.options.push({
        title: '默认选项',
        id: Date.now()
      })
    },
    handleDeleteOption(e, id) {
      e.options = e.options.filter((item) => item.id !== id)
      if (e.result === id) {
        e.result = e.options[0].id
      }
    },
    delScope(e) {
      this.ruleForm.scope = this.ruleForm.scope.filter(
        (item) => item.id !== e.id
      )
    },
    handleAddScope() {
      this.ruleForm.scope.push({
        id: Date.now(),
        min: 0,
        max: 100,
        title: '默认范围'
      })
    },
    handleToUserDetail(e) {
      this.$router.push({
        name: 'userDetail',
        query: {
          id: e.userId
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    margin-bottom: 30px;
  }
}
.box {
}
.box-card {
  display: inline-block;
  width: 32%;
  margin-right: 1%;
  .header {
    display: flex;
    align-items: flex-start;
  }
}
.scope-box {
  .scope-item {
    margin-right: 1%;
    display: inline-block;
    width: 20%;
  }
}
</style>
